import Vue from 'vue'
import store from '@/store'

// 是否为总公司
const isHeaderCompany = () => store.state.user.company_id === 1

// 权限校验是否通过
const checkPermission = (value) => {
  const roles = store.getters && store.getters.btnPermission
  // const roles = ['contract:opera']
  if (value === 'pre' || roles.indexOf('admin') !== -1) {
    return true
  }
  if (value && value instanceof Array && value.length > 0) {
    const permissionRoles = value

    const hasPermission = roles.some(role => permissionRoles.includes(role))

    return hasPermission
  } else {
    // 只做按钮级别权限控制。
    // 角色权限控制可能对按钮级别进行覆盖
    // contract:add contract:edit list操作级别
    // contract:opera 操作栏级别
    // contract:form:rent:add 关联级别
    throw new Error(`使用方式： v-permission="['contract:add', 'contract:edit', 'contract:opera', 'contract:form:xxx']"`)
  }
}

/**
 * 校验审核流程
 * @param {object} row 行
 * @param {string | array} value 检查值
 * @param {string}} key 权限标识
 */
const checkAudit = (row, value, key = 'custom_system_modulars') => {
  const checkModules = row?.[key]
  if (checkModules && checkModules instanceof Array) {
    value = typeof value === 'string' ? [value] : value
    return checkModules.some((item) => value.includes(item))
  }
  return false
}

/**
 * 检查行是否为自身创建
 */
const checkMyCreate = (row) => {
  const userId = store.getters && store.getters.userId
  const adminId = row?.admin_id
  return Number(adminId) === Number(userId)
}

// 花裤衩权限控制
const permission = {
  inserted(el, binding) {
    const { value } = binding
    const hasPermission = checkPermission(value)
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

const install = () => {
  // v-header 是否为总公司
  Vue.directive('header', {
    inserted(el) {
      const company_id = store.state && store.state.user.company_id
      if (company_id !== 1) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  })

  Vue.directive('permission', permission)

  // 全局属性挂载 保证每一个组件都能进行权限控制
  Vue.prototype.$checkPermission = checkPermission

  // 不做按需加载？ 保证后期其他页面加入可能会加载oa的可能
  Vue.prototype.$checkAudit = checkAudit

  //
  Vue.prototype.$checkMyCreate = checkMyCreate
}

export {
  isHeaderCompany,
  checkPermission,
  checkAudit
}

export default {
  install,
  isHeaderCompany
}
